
import CollaborativeFilttering.Estruturas.MusicSet;
import CollaborativeFilttering.FiltragemColaborativa;
import Configuracao.Autenticacao;
import DataAccess.Authentication;
import MDS.MDS;
import arcademis.ArcademisException;
import de.umass.lastfm.Period;
import de.umass.lastfm.Track;
import de.umass.lastfm.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import rme.server.RmeRemoteObject;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Pedro
 */
public class ObjetoRemotoImp extends RmeRemoteObject implements ObjetoRemoto {

    public static HashMap<String, Integer> redes = new HashMap<String, Integer>();
    private static int NetworkId;
    private static ArrayList<Integer> NetworkIdList = new ArrayList<Integer>();
    private static HashMap<Integer,FiltragemColaborativa> hashRedes = new HashMap<Integer, FiltragemColaborativa>();
    private static ArrayList<String> users = new ArrayList<String>();
    private static HashMap<String, ArrayList<MusicSet>> musicasPorUser = new HashMap<String, ArrayList<MusicSet>>();

    @Override
    public boolean isValidAuthentication(String nome, String password) throws ArcademisException {
        Authentication aut = Authentication.getInstance();
        return aut.isValidAuthentication(nome, password);
    }

    public int getCurrentNetworkId() throws ArcademisException {
        return ObjetoRemotoImp.NetworkId;
    }

    public int getNewNetworkId() throws ArcademisException {

        int retorno = 0;
        do {            
                
             retorno = (int) Math.round((float)(Math.random()*1000));
                
        } while (ObjetoRemotoImp.NetworkIdList.contains(retorno));

        ObjetoRemotoImp.NetworkIdList.add(retorno);
        this.PrintNetworksId();
        ObjetoRemotoImp.NetworkId = retorno;

        return retorno;
    }

    public String[] requestSongs(String userName, int networkId) throws ArcademisException {

        FiltragemColaborativa f = null;
        if(!users.contains(userName))
        {
           
            if (ObjetoRemotoImp.NetworkIdList.contains(networkId))
            {
               ObjetoRemotoImp.redes.put(userName, networkId);
               users.add(userName);
               
                if(hashRedes.containsKey(networkId))
                {
                  f = hashRedes.get(networkId);
                }else
                {
                   f = new FiltragemColaborativa();
                   hashRedes.put(networkId, f);
                }

                ArrayList<MusicSet> musicSets = new ArrayList<MusicSet>();
                List<Track> tracks = null;

                tracks = (List<Track>)User.getRecentTracks(userName,100, Autenticacao.APIkey,1).getPageResults();
                if(tracks.isEmpty())
                       tracks = (List<Track>)User.getTopTracks(userName,Period.OVERALL,Autenticacao.APIkey);

                for(Track t: tracks)
                {
                   musicSets.add((new MusicSet(t.getName(),t.getArtist())));
                }
                
                musicasPorUser.put(userName, musicSets);

                f.Filtrar(musicSets);
                f.aplicarCoeficienteDoCosseno();
                f.ordenaMusicas();
            }
         }
        
        f = hashRedes.get(ObjetoRemotoImp.redes.get(userName));
        if(f!=null)
        {
                
                MDS mds = new MDS(f);
                ArrayList<MusicSet> mapa = mds.getRecomendadas();
                String[] retorno = new String[mapa.size()];
                int i = 0;
                for(MusicSet d: mapa)
                {
                    retorno[i] = d.getMusica() + " - " +  d.getAutor();
                    i++;
                }
        
                return retorno;

            } else {
                return null;
            }
        }
    
    private void PrintNetworks() {
        Iterator i = ObjetoRemotoImp.redes.keySet().iterator();
        while (i.hasNext()) {
            String user = i.next().toString();
            System.out.println("Usuario :" + user + " - Na rede :" + ObjetoRemotoImp.redes.get(user));
        }

    }

    private void PrintNetworksId() {
        Iterator i = ObjetoRemotoImp.NetworkIdList.iterator();
        while (i.hasNext()) {
            String user = i.next().toString();
            System.out.println("Rede:" + user);
        }

    }

    public boolean retiraDaRede(String username, int networkId) throws ArcademisException {
        System.out.println("Vai retirar o usuario " + username + "da Rede");
        if(ObjetoRemotoImp.redes.containsValue(networkId))
        {
           if(ObjetoRemotoImp.redes.containsKey(username))
           {
               ObjetoRemotoImp.redes.remove(username);
               ArrayList<MusicSet> musicasDoUsuario = musicasPorUser.get(username);
               FiltragemColaborativa f = this.hashRedes.get(networkId);
               for(MusicSet m: musicasDoUsuario)
               {
                  MusicSet musica2 = f.musicasNaRede.get(f.musicasNaRede.indexOf(m));
                  if(musica2 != null)
                  {
                     if(musica2.getOcorrencia() > 1)
                         musica2.setOcorrencia(musica2.getOcorrencia() - 1);
                  }
               }
               if(!ObjetoRemotoImp.redes.containsValue(networkId))
                     if (hashRedes.containsKey(networkId))
                     {
                         System.out.println("Vai apagar a rede!");
                           hashRedes.remove(networkId);
                      }
               return true;
           }
        }
        return false;
    }

}
